package com.heima.leetcode.practice;

import java.util.*;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 347. 前 K 个高频元素
 * @date 2025/2/26 11:06
 */
public class E347 {

    public int[] topKFrequent1(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) map.compute(num, (key, value) -> value == null ? 1 : value + 1);
        List<Integer> list = map.entrySet().stream().sorted((o1, o2) -> o2.getValue() - o1.getValue()).map(Map.Entry::getKey).toList();
        return list.subList(0, k).stream().mapToInt(Integer::intValue).toArray();
    }

    public int[] topKFrequent2(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums)
            map.compute(num, (key, value) -> value == null ? 1 : value + 1);
        Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
        PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
        for (Map.Entry<Integer, Integer> entry : entrySet) {
            priorityQueue.offer(entry);
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            Map.Entry<Integer, Integer> entry = priorityQueue.poll();
            res[i] = entry.getKey();
        }
        return res;
    }
}
